package com.yupi.oj.manager;

import com.yupi.oj.common.ErrorCode;
import com.yupi.oj.exception.BusinessException;
import com.yupi.oj.model.entity.User;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
/**
 * 基础限流服务
 */
@Service
public class RedisLimitManager {
    @Resource
    private RedissonClient redissonClient;

    public void doRateLimit(String key, User loginUser){
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        Integer isVip = loginUser.getIsVip();
        //vip可相对频繁的提交
        if (isVip==1){
            rateLimiter.trySetRate(RateType.PER_CLIENT,1,1, RateIntervalUnit.SECONDS);
        }else if (isVip==0){
            rateLimiter.trySetRate(RateType.PER_CLIENT,1,3, RateIntervalUnit.SECONDS);
        }else {
            rateLimiter.trySetRate(RateType.PER_CLIENT,1,3, RateIntervalUnit.SECONDS);
        }
        boolean b = rateLimiter.tryAcquire(1);
        if (!b){
            throw new BusinessException(ErrorCode.TO_MANY_REQUEST);
        }
    }
}
